﻿using System;
using System.Xml;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;

namespace WF_CallerOrder
{
    public sealed partial class CallerOrder : SequentialWorkflowActivity
    {
        public CallerOrder()
        {
            InitializeComponent();
        }

        public Guid workflowId = default(System.Guid);
        public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();

        private void onWorkflowActivated1_Invoked(object sender, ExternalDataEventArgs e)
        {
            XmlDocument xd = new XmlDocument();
            xd.LoadXml(this.workflowProperties.AssociationData);

            foreach (XmlNode xn in xd.SelectSingleNode("workflows").ChildNodes)
            {
                Guid curWF = new Guid(xn.InnerText);
                SPWorkflowAssociation wrkFl = this.workflowProperties.List.WorkflowAssociations[curWF];

                try
                {
                    //if (this.workflowProperties.Item.Workflows[curWF] != null)
                    //{
                        //se un wrokflow è già attivo su un SPListItem devo rimuoverlo
                        //e riassociarlo

                        //nel caso del Sync, devo rimuoverlo perchè è appeso in attesa
                        //della delete per cui parte prima della Copia
                        //andrebbe tolto dal codice del WF Sync il fatto che attende 
                        //una modifica (solo su Activated deve partire)
                        //in questo modo però, se CallerOrder lo richiama su modifica
                        //deve ripartire

                        //if (this.workflowProperties.Item.Workflows[curWF].ParentItem != null)
                        //    this.workflowProperties.Site.WorkflowManager.RemoveWorkflowFromListItem(this.workflowProperties.Item.Workflows[curWF]);
                    //    if (this.workflowProperties.Item.Workflows[curWF].ParentAssociation != null)
                    //    {
                    //        if (this.workflowProperties.Item.Workflows[curWF].ParentAssociation.Name.Equals(wrkFl.Name))
                    //        {
                    //            this.workflowProperties.Site.WorkflowManager.RemoveWorkflowFromListItem(this.workflowProperties.Item.Workflows[curWF]);
                    //        }
                    //    }
                    //}
                    SPWorkflow toRemove = CheckIfWorkflowIsInstanciated(this.workflowProperties.Item, wrkFl.Name);
                    if (toRemove != null)
                    {
                        this.workflowProperties.Site.WorkflowManager.RemoveWorkflowFromListItem(toRemove);
                    }
                }
                catch (Exception ex)
                {
                    //SPListItem err = this.workflowProperties.HistoryList.Items.Add();
                    //err["Title"] = string.Format("Error on remove WF {0} - {1}", xn.InnerText, ex.Message);
                    //err.SystemUpdate();
                }

                try
                {
                    this.workflowProperties.Site.WorkflowManager.StartWorkflow(this.workflowProperties.Item, wrkFl, wrkFl.AssociationData);
                }
                catch (Exception ex)
                {
                    //SPListItem err = this.workflowProperties.HistoryList.Items.Add();
                    //err["Title"] = string.Format("Error on call WF {0} - {1}", xn.InnerText, ex.Message);
                    //err.SystemUpdate();
                }
            }
        }

        private SPWorkflow CheckIfWorkflowIsInstanciated(SPListItem i, string WFName)
        {
            SPWorkflow ret = null;
            SPWorkflowCollection instanciatedWF = this.workflowProperties.Site.WorkflowManager.GetItemWorkflows(i, new SPWorkflowFilter(SPWorkflowState.Running, SPWorkflowState.Completed));
            if (instanciatedWF.Count > 0)
            {
                foreach (SPWorkflow wf in instanciatedWF)
                {
                    if (wf.ParentAssociation.Name.Equals(WFName))
                    {
                        ret = wf;
                        break;
                    }
                }
            }
            return ret;
        }
    }
}
